package br.com.farmabid.email;

import java.io.IOException;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import br.com.caelum.vraptor.freemarker.Freemarker;
import br.com.farmabid.component.StringUteis;
import br.com.farmabid.persistence.AbstractDAO;
import br.com.farmabid.usuario.Usuario;
import freemarker.template.TemplateException;

@Named("emailDAO")
public class EmailDAO extends AbstractDAO {
	private static final long serialVersionUID = 1047577683248831575L;
	private ConfiguracaoEmail mailConfig;
	@Inject private Freemarker freemaker;
	
	public EmailDAO(EntityManager manager) {
		this.manager = manager;
	}
	
	public EmailDAO(){}
	
	public Boolean envioEmailCadastrado(String emailDestino, Usuario user){
		String msg = "";
		try {
			msg = freemaker.use("/emailCadastrado").with("user", user).getContent();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		}
		Email email = criaEmail("farmabid@farmabid.com.br", emailDestino, msg);
		email.setSubject("Conta no Farmabid");
		return enviaEmail(email);
	}
	
	public Boolean envioEmailNovoUsuarioAdmin(String emailDestino, Usuario user){
		String msg = "Um novo usuário se cadastrou no sistema: <br><Br> " + user.getNome() + " - " + user.getEmail();
		Email email = criaEmail("farmabid@farmabid.com.br", emailDestino, msg);
		email.setSubject("Novo cadastro no Farmabid");
		return enviaEmail(email);
	}

	private Boolean enviaEmail(Email email) {
		try {
			email.send();
			return true;
		} catch (EmailException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private ConfiguracaoEmail getMailConfig(){
		if(mailConfig == null){
			mailConfig = manager.find(ConfiguracaoEmail.class, 1);
		}
		return mailConfig;
	}
	
	private Email criaEmail(String emailFrom, String emailTo, String msg){
		ConfiguracaoEmail mail = getMailConfig();
		HtmlEmail email = new HtmlEmail();
		email.setHostName(mail.getHost());
		email.setSmtpPort(mail.getPorta());
		email.setAuthenticator(new DefaultAuthenticator(mail.getUsuario(), mail.getSenha()));
		email.setSSLOnConnect(true);
		try {
			email.getMailSession().getProperties().put("mail.smtps.auth", "true");
			email.getMailSession().getProperties().put("mail.debug", "true");
			email.getMailSession().getProperties().put("mail.smtps.port", mail.getPorta());
			email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", mail.getPorta());
			email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
			email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
			email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
			if(!StringUteis.isEmpty(emailFrom)){
				email.setFrom(emailFrom);
			} else {
				email.setFrom(mail.getNomeEmail());
			}
			email.setHtmlMsg(msg);
			email.addTo(emailTo);
		} catch (EmailException e) {
			e.printStackTrace();
		}
		return email;
	}
	
	public Boolean enviaNovaSenha(String novaSenha, Usuario user){
		try {
			String msg = freemaker.use("/novaSenha").with("user", user).with("novaSenha", novaSenha).getContent();
			Email email = criaEmail("farmabid@farmabid.com.br", user.getEmail(), msg);
			email.setSubject("Senha Alterada no Farmabid");
			enviaEmail(email);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
}